/**
 * 商品管理页
 * 
 * 设计：宋福勇
 * 
 * 审核优化：周俊伟
 * 
 * 最后修改日期:2020-09-17
 */
const app = getApp()
const db = wx.cloud.database();
const _ = db.command;

function add(num1, num2) {
    const num1Digits = (num1.toString().split('.')[1] || '').length;
    const num2Digits = (num2.toString().split('.')[1] || '').length;
    const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
}

function accMul(arg1, arg2) {
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) {}
    try { m += s2.split(".")[1].length } catch (e) {}
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
//给Number类型增加一个mul方法，调用起来更加方便。
Number.prototype.mul = function(arg) {
    return accMul(arg, this);
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        //用于分页的参数
        start_page: 0,
        limit_page: 10,
        stop_page: 0,
        edit_goods: [],
        search_code: false,
        goods: [],
        edit: 0,
        edit_id: 0,
        // 开始
        touchS: 0,
        // 移动
        touchM: 0,
        // 结束
        touchE: 0,
        //总距离
        TotalDistancea: 0,
        // 判断移动哪一个物品
        delete_btn: -1,
        zcb: '0.00',
        zkc: '0.00',
        // 货品信息
        goods: [],
        showModalStatus: false
    },
    onLoad: function(options) {
        //获取购物车中的物品
        this.goods()
    },
    // 删除物品
    delete(e) {
        if(app.globalData.guest == '1'){
            wx.showModal({
              content: '抱歉,体验账号不支持此操作,请注册后再试!',
              showCancel:false,
            })
            return false;
        }
        var that = this;
        let goods = this.data.goods;
        var edit_goods = goods[e.currentTarget.dataset.delete];
        var sptm = goods[e.currentTarget.dataset.delete].bz;
        wx.showModal({
            content: '你确定要删除:' + goods[e.currentTarget.dataset.delete].goods_title + '的商品吗?',
            success: function(res) {
                if (res.confirm) {
                    goods.splice(e.currentTarget.dataset.delete, 1)
                    wx.cloud.callFunction({
                        name: 'commodity',
                        data: {
                            del_goods: true,
                            user_id: app.globalData.user_id,
                            sptm: sptm,
                        },
                        complete: res => {
                            console.log(res);
                        }
                    })
                    that.setData({
                        goods,
                    })
                    that.goods_count();
                }
            }
        })
    },
    search_goods(e) {
        var that = this;
        var value = e.detail.value;
        if (value == '') {
            this.setData({
                start_page: 0,
                limit_page: 10,
                stop_page: 0,
                edit_goods: [],
                search_code: false,
                goods: [],
                edit: 0,
                edit_id: 0,
            })
            this.goods();
        } else {
            this.setData({
                search_code: true
            })
            wx.cloud.callFunction({
                name: 'commodity',
                data: {
                    search_goods: true,
                    user_id: app.globalData.user_id,
                    value: value,
                },
                complete: res => {
                    wx.hideLoading();
                    console.log(res);
                    if (res.result.list.length > 0) {
                        let goods = res.result.list[0].goods;
                        this.setData({
                            goods: goods
                        })
                        that.goods_count();
                    } else {
                        wx.showModal({
                            content: '未找到对应商品',
                            showCancel:false,
                        })
                    }
                }
            })
        }
    },
    // 开始滑动时
    touchS(e) {
        let op = e.currentTarget.dataset.delete_btn
        let i = e.changedTouches[0].clientX
        console.log(i);
        if (this.data.delete_btn != op) {
            this.setData({
                TotalDistancea: 0
            })
        }
        this.setData({
            touchS: i,
            delete_btn: op
        })
    },
    // 正在滑动时
    touchM(e) {
        let touchS = this.data.touchS;
        let i = e.changedTouches[0].clientX
        console.log(i);
        if (touchS > i) {
            if (this.data.TotalDistancea < 86) {
                let TotalDistancea = touchS - i;
                if (TotalDistancea < 86) {
                    this.setData({
                        touchM: i,
                        TotalDistancea: TotalDistancea
                    })
                }
            }
        }
    },
    // 结束滑动时
    touchE(e) {
        let touchS = this.data.touchS;
        let i = e.changedTouches[0].clientX;
        let TotalDistancea = touchS - i;
        console.log(i);
        if (TotalDistancea < 43) {
            this.setData({
                TotalDistancea: 0
            })
        } else {
            this.setData({
                TotalDistancea: 86
            })
        }
    },
    showModalStatus() {
        if (this.data.showModalStatus == false) {
            this.setData({
                showModalStatus: true
            })
        } else {
            this.setData({
                showModalStatus: false
            })
        }
    },
    //统计总库存和总成本
    goods_count() {
        var zcb = 0;
        var zkc = 0;
        var goods = this.data.goods;
        for (var i = 0; i < goods.length; i++) {
            zkc = parseInt(zkc + parseInt(goods[i].goods_num));
            zcb = add(zcb, accMul(goods[i].goods_price, goods[i].goods_num))
        }
        this.setData({
            zkc: zkc,
            zcb: app.gsh_money(zcb),
        })
    },
    //获取购物车中的物品
    goods() {
        wx.showLoading({ title: '加载商品中', })
        var that = this;
        if (that.data.stop_page == '1') {
            wx.showToast({
                icon: 'none',
                title: '商品已加载完毕',
            })
        } else {
            wx.cloud.callFunction({
                name: 'commodity',
                data: {
                    search: true,
                    user_id: app.globalData.user_id,
                    start_page: that.data.start_page,
                    end_page: that.data.start_page + that.data.limit_page,
                },
                complete: res => {
                    wx.hideLoading();
                    console.log(res);
                    if (res.result.data.length > 0) {
                        //判断是否分页加载完毕
                        if (res.result.data.length < that.data.limit_page) {
                            that.setData({
                                stop_page: 1,
                            })
                        }
                        let goods = res.result.data[0].goods;
                        this.setData({
                            goods: that.data.goods.concat(goods)
                        })
                        that.goods_count();
                    }
                }
            })
        }
    },
    //编辑商品
    editgoods(e) {
        if(app.globalData.guest == '1'){
            wx.showModal({
              content: '抱歉,体验账号不支持此操作,请注册后再试!',
              showCancel:false,
            })
            return false;
        }
        var id = e.currentTarget.dataset.delete_btn;
        console.log("正在编辑商品ID:" + id);
        console.log(this.data.goods[id]);
        this.setData({
            edit: 1,
            edit_goods: this.data.goods[id],
            edit_id: id,
        })
        this.showModalStatus();
    },
    // 添加商品
    goodsAdd(e) {
        if(app.globalData.guest == '1'){
            wx.showModal({
              content: '抱歉,体验账号不支持此操作,请注册后再试!',
              showCancel:false,
            })
            return false;
        }
        var that = this;
        let goods = this.data.goods
        let data = e.detail.value
            //空判断
        if (data.goods_title == '') { this.alert("请输入商品名称"); return false; }
        if (data.goods_num == '') { this.alert("请输入商品数量"); return false; }
        if (data.goods_price == '') { this.alert("请输入商品进价"); return false; }
        if (data.goods_amount == '') { this.alert("请输入商品售价"); return false; }
        if (data.bz == '') { this.alert("请输入商品条码"); return false; }
        data.goods_num = parseInt(data.goods_num);
        data.goods_price = app.gsh_money(data.goods_price)
        data.goods_amount = app.gsh_money(data.goods_amount);
        //新增模式
        if (this.data.edit == '0') {
            goods.push(data);
            wx.cloud.callFunction({
                    name: 'commodity',
                    data: {
                        add_goods: true,
                        add: true,
                        user_id: app.globalData.user_id,
                        sptm: data.bz,
                        sptm2: data.bz2,
                        goods_list: data,
                    },
                    complete: res => {
                        console.log(res);
                    }
                })
                //编辑模式
        } else {
            goods[this.data.edit_id] = data;
            wx.cloud.callFunction({
                name: 'commodity',
                data: {
                    add_goods: true,
                    edit: true,
                    user_id: app.globalData.user_id,
                    sptm: data.bz,
                    sptm2: data.bz2,
                    goods_list: data,
                },
                complete: res => {
                    console.log(res);
                }
            })
        }
        this.setData({
            edit_goods: [],
            edit: 0,
            edit_id: 0,
            goods: goods,
            showModalStatus: false
        });
        that.goods_count();
    },
    phone_code(){
        var that = this
        var edit_goods = []
        wx.scanCode({
            success(res) {
                that.setData({
                    edit_goods:{
                        bz:res.result
                    }
                })
            }
        });
    },
    barcode(e){
        var that = this
        wx.scanCode({
            success(res) {
                that.setData({
                    tm:res.result
                })
                e.detail.value = res.result;
                that.search_goods(e);
            }
        });

    },
    // 点击朦版关闭弹框
    powerDrawer() {
        if (this.data.showModalStatus == true) {
            this.setData({
                showModalStatus: false,
                edit_goods: [],
                edit: 0,
                edit_id: 0,
            })
        }
    },
    alert(text) {
        wx.showModal({
            content: text,
            showCancel: false,
        })
    },
    onReachBottom: function() {
        var that = this
        if (this.data.search_code == false) {
            var PAGE = that.data.page + 1
            console.log('上一页:', that.data.page)
            that.setData({
                page: PAGE
            })
            wx.showLoading({
                title: "加载中"
            })
            this.goods();
            wx.hideLoading();
        }
    }
})